const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const db = require('./db/my') 
const index = require('./routes/index')
const users = require('./routes/users')
const corp = require('./routes/corp')
const Koacors = require('koa-cors')

// error handler
onerror(app)

// middlewares
// 调用中间件
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
// 允许所有来源的请求
app.use(Koacors())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
// ctx.response.body="" 返回数据给页面
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})


// 查询
async function executeQuery(query) {
  return new Promise((resolve, reject) => {
    db.query(query, (error, results, fields) => {
      if (error) {
        reject(error);
      } else {
        resolve(results);
      }
    });
  });
}

// routes
// app.use(启动路由，允许任何请求)
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(corp.routes(), corp.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
  
});




module.exports = app
